import { View } from "@tarojs/components";
import { Navbar, Avatar, Image } from "@taroify/core";
import { Cross, Sign } from "@taroify/icons";
import Taro, { useLoad } from "@tarojs/taro";
import { useState } from "react";
import { getUser } from "@/utils/auth";
import { ListPropsType, UserType } from "@/types";
import upload from "@/api/upload";
import { copyToClipboard, toast, chooseImg, updateUser } from "@/utils";
import List from "@/components/List";

export default () => {
  const [user, setUser] = useState<UserType>(getUser());
  const [flag, setFlag] = useState<{ avatar: boolean; background: boolean }>({
    avatar: false,
    background: false,
  });
  useLoad(() => setUser(getUser()));
  async function uploadImage(key) {
    setFlag((pre) => ({ ...pre, [key]: true }));
    const res = await chooseImg();
    setKey(key, res);
  }
  function setKey(key: string, value) {
    setUser((prevUser) => ({ ...prevUser, [key]: value }));
  }

  const options: Array<ListPropsType> = [
    {
      label: "昵称",
      value: user?.nickname,
      flag: true,
      setValue: (v) => setKey("nickname", v),
      right: "",
    },
    {
      label: "ID",
      value: (
        <View>
          {user?.ID}
          <Sign size={20} onClick={() => copyToClipboard(user?.ID)} />
        </View>
      ),
      right: "",
    },
    {
      label: "邮箱",
      value: user?.email,
      flag: true,
      setValue: (v) => setKey("email", v),
      right: "",
    },
    {
      label: "手机号",
      value: user?.phone,
      flag: true,
      setValue: (v) => setKey("phone", v),
      right: "",
    },

    {
      label: "简介",
      value: user?.intro,
      flag: true,
      setValue: (v) => setKey("intro", v),
      right: "",
    },
    {
      label: "背景设置",
      value: (
        <View onClick={() => uploadImage("background")}>
          <Image mode="widthFix" src={user?.background} className="w-full" />
        </View>
      ),
    },
  ];
  async function save() {
    console.log(flag);
    flag.avatar && setKey("avatar", await upload(user.avatar));
    flag.background && setKey("background", await upload(user.background));
    updateUser(user).then((res) => {
      console.log("Saved");
      Taro.reLaunch({ url: "/pages/more/more" });
    });
  }
  return (
    <View>
      <Navbar>
        <Navbar.NavLeft icon={<Cross color="#ccc" />}></Navbar.NavLeft>
        <Navbar.Title>编辑个人资料</Navbar.Title>
        <Navbar.NavRight onClick={save}>保存</Navbar.NavRight>
      </Navbar>
      <View className="flex justify-center items-center gap-4 flex-col ">
        <Avatar
          onClick={() => uploadImage("avatar")}
          src={user?.avatar}
          size="large"
        />
        <List options={options} />
      </View>
    </View>
  );
};
